package com.gushen.library.filter;

import android.content.Context;
import android.graphics.*;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import com.gushen.library.ShaderContents;
import com.gushen.library.WatermarkConfig;
import com.gushen.library.utils.FileUtils;
import com.gushen.library.utils.OpenGLUtils;


/**
 * 贴纸滤镜
 */
public class TimeFilter extends AbstractFrameFilter {

    private Bitmap mBitmap;
    private Canvas bitmapCanvas;
    private Paint textPaint;
    int[] mTextureId ;
    private float textHeight;
    private float defaultTextSize = 12f;

    public TimeFilter(Context context) {
        super(context, ShaderContents.base_vertex, ShaderContents.base_frag);
        mTextureId = new int[1];
    }


    @Override
    public void onReady(int width, int height) {
        super.onReady(width, height);
        initBitmapCanvas();
    }

    //设置水印
    private WatermarkConfig watermarkConfig;
    public void setWaterMarkConfig(WatermarkConfig config) {
        this.watermarkConfig = config;
        //文本模式，不支持自动换行
        if (textPaint != null && config.getWaterMarkType() == WatermarkConfig.WATERMARK_TYPE_TEXT){
            if (config.getTextSize() > 0){
                defaultTextSize = config.getTextSize();
            }
            textPaint.setTextSize(FileUtils.dp2px(defaultTextSize));
            textPaint.setColor(config.getTextColor());
            textHeight = (textPaint.getFontMetrics().descent - textPaint.getFontMetrics().ascent) * 1.1f;
        }
    }


    @Override
    public int onDrawFrame(int textureId) {

        //设置了视口的大小，这里将视口设置为整个输出窗口的大小，mOutputWidth和mOutputHeight分别代表输出窗口的宽度和高度。
        GLES20.glViewport(0, 0, mOutputWidth, mOutputHeight);
        //将帧缓冲区绑定到当前的OpenGL上下文，这样所有的绘制操作都会被渲染到这个帧缓冲区中。
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[0]);



        //激活了一个着色器程序，这个程序定义了如何处理顶点和片段着色。
        GLES20.glUseProgram(mGLProgramId);


        //传递坐标
        mGLVertexBuffer.position(0);
        GLES20.glVertexAttribPointer(vPosition, 2, GLES20.GL_FLOAT, false, 0, mGLVertexBuffer);
        GLES20.glEnableVertexAttribArray(vPosition);

        mGLTextureBuffer.position(0);
        GLES20.glVertexAttribPointer(vCoord, 2, GLES20.GL_FLOAT, false, 0, mGLTextureBuffer);
        GLES20.glEnableVertexAttribArray(vCoord);





        //因为这一层是摄像头后的第一层，所以需要使用扩展的  GL_TEXTURE_EXTERNAL_OES
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
        GLES20.glUniform1i(vTexture, 0);


        // 绘制三角形
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);

        // 解绑纹理和帧缓冲区
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);

        // 开启混合模式
        GLES20.glEnable(GLES20.GL_BLEND);
        GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);


//        String aText = textFormat.format(new Date());
//        mBitmap.eraseColor(Color.TRANSPARENT);
//        bitmapCanvas.drawText(aText, 1, 1.0f + mBitmap.getHeight() * 0.75f, textPaint);
        if (watermarkConfig != null){
            mBitmap.eraseColor(Color.TRANSPARENT);
            if (watermarkConfig.getWaterMarkType() == WatermarkConfig.WATERMARK_TYPE_BITMAP && watermarkConfig.getBitmapWatermark() != null){
                bitmapCanvas.drawBitmap(watermarkConfig.getBitmapWatermark(), 0, 0, textPaint);
            }else if (watermarkConfig.getWaterMarkType() == WatermarkConfig.WATERMARK_TYPE_TEXT){
                String textWatermark = watermarkConfig.getTextWatermark();
                if (textWatermark.contains("\n")){
                    String[] split = textWatermark.split("\n");
                    for (int i = 0; i < split.length; i++) {
                        bitmapCanvas.drawText(split[i], 1,  textHeight + textHeight * i, textPaint);
                    }
                }
            }
        }

        int x = 20;
        if (watermarkConfig != null && watermarkConfig.getLeftMargin() > 0){
            x = watermarkConfig.getLeftMargin();
        }

        int y = 30;
        if (watermarkConfig != null && watermarkConfig.getTopMargin() > 0){
            y = watermarkConfig.getTopMargin();
        }

        // 设置新的视口位置
        GLES20.glViewport(x, y,
                mBitmap.getWidth(),
                mBitmap.getHeight());

        // 绑定帧缓冲区
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[0]);
        //使用着色器
        GLES20.glUseProgram(mGLProgramId);


        //传递坐标
        mGLVertexBuffer.position(0);
        GLES20.glVertexAttribPointer(vPosition, 2, GLES20.GL_FLOAT, false, 0, mGLVertexBuffer);
        GLES20.glEnableVertexAttribArray(vPosition);

        mGLTextureBuffer.position(0);
        GLES20.glVertexAttribPointer(vCoord, 2, GLES20.GL_FLOAT, false, 0, mGLTextureBuffer);
        GLES20.glEnableVertexAttribArray(vCoord);

        // 激活着色器程序
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);

        // 绑定位图纹理
        OpenGLUtils.glGenTextures(mTextureId);
        //表示后续的操作 就是作用于这个纹理上
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureId[0]);
        // 将 Bitmap与纹理id 绑定起来
        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, mBitmap, 0);
        GLES20.glUniform1i(vTexture, 0);

        // 绘制三角形
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);


        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);

        //关闭
        GLES20.glDisable(GLES20.GL_BLEND);

        // 重置视口位置
        GLES20.glViewport(0, 0, mOutputWidth, mOutputHeight);

        // 释放纹理资源
        GLES20.glDeleteTextures(mTextureId.length, mTextureId, 0);

        //返回fbo的纹理id
        return mFrameBufferTextures[0];
    }


    private void initBitmapCanvas() {
        float aFontSize = mOutputWidth / 15;
        textPaint = new Paint();
        textPaint.setTextSize(aFontSize);
        textPaint.setFakeBoldText(false);
        textPaint.setAntiAlias(true);
        textPaint.setColor(Color.WHITE);

        mBitmap = Bitmap.createBitmap(mOutputWidth , mOutputWidth, Bitmap.Config.ARGB_8888);

        // Creates a new canvas that will draw into a bitmap instead of rendering into the screen
        bitmapCanvas = new Canvas(mBitmap);
    }



    @Override
    public void release() {
        super.release();
        mBitmap.recycle();
    }
}
